package com.ruoyi.web.controller.ex;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.doudou.core.container.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.ex.domain.AnswerVo;
import com.ruoyi.ex.domain.ExExcelQuestion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ex.domain.ExQuestion;
import com.ruoyi.ex.service.IExQuestionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 题目Controller
 *
 * @author zzx
 * @date 2023-03-23
 */
@Api("题目")
@RestController
@RequestMapping("/ex/question")
public class ExQuestionController extends BaseController {

    @Autowired private IExQuestionService exQuestionService;

    /**
     * 根据题库查询题目集合
     */
    @GetMapping("/ids-bank/{bankId}")
    @ApiOperation("根据题库查询题目集合")
    public AjaxResult idsBeabk(@PathVariable("bankId") Long bankId) {
        return success(exQuestionService.selectIdsByBankId(bankId));
    }

    /**
     * 查询题目列表
     */
    @GetMapping("/list")
    @ApiOperation("查询题目列表")
    public TableDataInfo list(ExQuestion exQuestion) {
        exQuestion.setDeptId(getDeptId());
//        startPage();
        //先修改为默认500条
        PageDomain pageDomain = TableSupport.buildPageRequest();
        PageHelper.startPage(pageDomain.getPageNum(), 500);
        List<ExQuestion> list = exQuestionService.selectExQuestionList(exQuestion);
        return getDataTable(list);
    }

    /**
     * 导出题目列表
     */
    @PreAuthorize("@ss.hasPermi('ex:question:export')")
    @Log(title = "题目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExQuestion exQuestion) {
        exQuestion.setId(getDeptId());
        List<ExQuestion> list = exQuestionService.selectExQuestionList(exQuestion);
        ExcelUtil<ExQuestion> util = new ExcelUtil<ExQuestion>(ExQuestion.class);
        util.exportExcel(response, list, "题目数据");
    }

    /**
     * 导出模板
     */
    @PreAuthorize("@ss.hasPermi('ex:question:exportModel')")
    @Log(title = "题目模板导出", businessType = BusinessType.EXPORT)
    @PostMapping("/importModel")
    public void importModel(HttpServletResponse response) {
        List<ExExcelQuestion> list = ListUtil.list(false);
        ExcelUtil<ExExcelQuestion> util = new ExcelUtil<ExExcelQuestion>(ExExcelQuestion.class);
        util.exportExcel(response, list, "题目模板");
    }

    /**
     * 导入
     */
    @PreAuthorize("@ss.hasPermi('ex:question:import')")
    @Log(title = "题目导入",businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importExcel(@RequestParam("file")MultipartFile file,@RequestParam("bankId")Long backId) throws Exception {
        ExcelUtil<ExExcelQuestion> util = new ExcelUtil<ExExcelQuestion>(ExExcelQuestion.class);
        List<ExExcelQuestion> exExcelQuestions = util.importExcel(file.getInputStream());
        //复制对象
        List<ExQuestion> exQuestionList = ListUtil.list(true);
        Long deptId = getDeptId();
        ExQuestion exQuestion;
        for (ExExcelQuestion question : exExcelQuestions) {
            exQuestion = new ExQuestion();
            exQuestion.setDeptId(deptId);
            exQuestion.setBankId(backId);
            exQuestion.setContent(question.getContent());
            exQuestion.setType(question.getType());
            exQuestion.setOptionList(parseAnswers(question));
            exQuestion.parseOptions();
            exQuestionList.add(exQuestion);
        }
        int i = exQuestionService.insertExQuestionAll(exQuestionList);
        exQuestionService.cacheQuestions(backId);
        return success(i);
    }

    private List<AnswerVo> parseAnswers(ExExcelQuestion question){
        List<AnswerVo> list = ListUtil.list(true);
        AnswerVo answerVo;
        String answers = question.getAnswers();
        JSONObject object = JSONUtil.parseObj(question);
        if ((answerVo = parseAnswers('a', object, answers)) != null){list.add(answerVo);}
        if ((answerVo = parseAnswers('b', object, answers)) != null){list.add(answerVo);}
        if ((answerVo = parseAnswers('c', object, answers)) != null){list.add(answerVo);}
        if ((answerVo = parseAnswers('d', object, answers)) != null){list.add(answerVo);}
        if ((answerVo = parseAnswers('e', object, answers)) != null){list.add(answerVo);}
        return list;
    }

    private AnswerVo parseAnswers(char key, JSONObject question,String answers){
        String keyStr = String.valueOf(key);
        return StrUtil.isNotBlank(question.getStr(keyStr)) ?
                AnswerVo.builder().k((char)(key - 32)).v(question.getStr(keyStr)).r(StrUtil.containsIgnoreCase(answers,keyStr)).build() :
                null;
    }

    /**
     * 获取题目详细信息
     */

    @GetMapping(value = "/{id}")
    @ApiOperation("获取题目详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(exQuestionService.selectExQuestionById(id));
    }

    /**
     * 根据ids获取题目详细信息
     */

    @PostMapping(value = "/by-ids")
    @ApiOperation("获取题目详细信息")
    public AjaxResult getInfo(@RequestBody JSONArray ids) {
        return success(exQuestionService.selectExQuestionByIds(ids.toList(Long.class)));
    }

    /**
     * 新增题目
     */
    @PreAuthorize("@ss.hasPermi('ex:question:add')")
    @Log(title = "题目", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增题目")
    public AjaxResult add(@RequestBody ExQuestion exQuestion) {
        exQuestion.setDeptId(getDeptId());
        int i = exQuestionService.insertExQuestion(exQuestion);
        exQuestionService.cacheQuestions(exQuestion.getBankId());
        return toAjax(i);
    }

    /**
     * 修改题目
     */
    @PreAuthorize("@ss.hasPermi('ex:question:edit')")
    @Log(title = "题目", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改题目")
    public AjaxResult edit(@RequestBody ExQuestion exQuestion) {
        int i = exQuestionService.updateExQuestion(exQuestion);
        exQuestionService.cacheQuestions(exQuestion.getBankId());
        return toAjax(i);
    }

    /**
     * 删除题目
     */
    @PreAuthorize("@ss.hasPermi('ex:question:remove')")
    @Log(title = "题目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除题目")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(exQuestionService.deleteExQuestionByIds(ids));
    }
}
